// pages/my/leaveMsg.js
const app = getApp();
var topOpacity = 0;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    // 组件参数设置，传递到组件
    defaultData: {
      title: "业主共创", // 导航栏标题
      showHome: false, //是否显示回到首页按钮
      showBack: true, //是否显示返回按钮
      showLogo: false, //是否显示logo
      bgColor: 'transparent'
    },
    baseUrl: app.baseUrl,
    version: app.globalData.version,
    navBarHeight: app.globalData.navBarHeight,
    publicContent: "",

    images: [], //上传图片集合
    isHeightModeArr: [],
    imgMax: 10, //上传图片的大小限制M
    tabId: 0,
    noteMaxLen: 300,
    imgArr: [],

    authData: {
      authType: '0', //0表示使用登录弹窗  1表示使用完善昵称头像弹窗 2表示直接弹出头像昵称选择框
      authUsername: "false", //是否已经授权头像昵称
    },
    showLogin: false, //是否显示授权弹窗
    showWsInfoDom: false, //直接显示头像昵称弹窗
    showPrivacyFlag: app.globalData.showPrivacyFlag,

    list: [],
    openid: '',
    shareTitle: '',
    shareImg: '',
    imgMax: 0,
    images: [],
    sendImgArr: [], //提交数据时的图片
    textareaContent: '请写下您的点赞描述',
    tipsText:''
  },
  onPageScroll(t) {
    if (t.scrollTop < 40) {
      topOpacity = 0
      if (this.data.topOpacity != 0) {
        this.setData({
          topOpacity: 0
        })
      }
    } else if (t.scrollTop >= 40) {
      if (topOpacity <= 1) {
        topOpacity = t.scrollTop / 100 - .4
      } else {
        topOpacity = 1
      }
      if (topOpacity <= 1) {
        this.setData({
          topOpacity: topOpacity
        })
      }
    }
  },
  recommend() {
    let that = this;
    that.setData({
      tabId: 0,
      textareaContent:'请写下您的点赞描述',
      tipsText:''
    })
  },
  historyRecommend() {
    let that = this;
    that.setData({
      tabId: 1,
      textareaContent: '请写下您的建议描述',
      tipsText:'此投诉为本小程序自有投诉渠道,非微信官方投诉渠道'
    })
  },
  //描述输入框
  partPro: function (e) {
    var value = e.detail.value,
      len = parseInt(value.length);
    if (len > this.data.noteMaxLen) return;
    this.setData({
      publicContent: value,
      currentNoteLen: len //当前字数
    })
  },


  //上传图片
  upLoadImg: function (e) {
    let that = this;

    //判断是否同意了引导协议
    if (app.globalData.showPrivacyFlag == false) {
      that.setData({
        showPrivacy: true
      })
      return;
    }

    wx.chooseImage({
      count: 5 - that.data.images.length,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: res => {
        let tempFilePaths = res.tempFilePaths;
        console.log(tempFilePaths)
        let images = that.data.images;
        let isHeightModeArr = that.data.isHeightModeArr;
        if ((images.length + tempFilePaths.length) > 4) {
          app.showTip("最多只能上传4张");
          return;

        }
        for (var item in res.tempFilePaths) {
          that.data.images.push(res.tempFilePaths[item]);
          isHeightModeArr.push(false);
          tempFilePaths = that.data.images;
        }
        //限制上传图片大小为5M,所有图片少于5M才能上传
        let size = res.tempFiles.every(item => {
          return item.size <= parseInt(that.data.imgMax) * 1024 * 1024
        })
        if (size) {
          that.setData({
            images: tempFilePaths,
            isHeightModeArr: isHeightModeArr
          })
        } else {
          app.showTip("上传图片不能大于" + that.data.imgMax + "M哦");

        }
      }
    })
  },

  //提交建议
  addLeaveMsg() {
    var that = this;
    var question = that.data.publicContent.trim();
    if (question == '') {
      app.showTip('请输入问题描述');
      return;
    }
    //提交图片至服务器
    that.sendFj();
    // if (that.data.images.length > 0) {
    //   //提交图片至服务器
    //   that.sendFj();
    // }
  },

  //提交图片附件到服务器
  sendFj() {
    var that = this;

    wx.showLoading({
      title: '建议提交中...'
    });

    //上传了图片
    if (that.data.images.length > 0) {
      for (var i = 0; i < that.data.images.length; i++) {
        wx.uploadFile({
          url: that.data.baseUrl + "uploadsLeaveMsg.php", //服务器接口
          method: 'POST',
          filePath: that.data.images[i],
          header: {
            'content-type': 'multipart/form-data'
          },
          name: 'file', //服务器定义的Key值
          formData: {},
          success: function (res) {
            //wx.hideLoading();
            console.log(res.data);
            if (res.data) {
              var sendImgArr = that.data.sendImgArr;
              sendImgArr.push(res.data);
              that.setData({
                sendImgArr: sendImgArr
              });

              if (that.data.images.length == that.data.sendImgArr.length) {
                //调用最终上传数据
                wx.hideLoading();
                that.sub();
              }
            } else {
              app.showTip('服务器保存图片失败,请刷新页面重试');
            }
          },
          fail: function () {
            wx.hideLoading();
            app.showTip('服务器繁忙,请稍候重试');
          }
        });
      }
    }else{
      wx.hideLoading();
      that.sub();
    }

  },


  //提交内容至数据库
  sub() {
    var that = this;

    wx.showLoading({
      title: '建议提交中...'
    });

    wx.request({
      url: that.data.baseUrl + 'addLeaveMsg.php',
      method: 'POST',
      data: {
        'openid': that.data.openid,
        'question': that.data.publicContent,
        'imgArr': JSON.stringify(that.data.sendImgArr),
        'question_type':that.data.tabId
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        wx.hideLoading();
        app.showTip(res.data['msg']);
        if (res.data.status == 1) {
          //清空数据
          that.setData({
              images: [],
              sendImgArr: [],
              publicContent:'',
              currentNoteLen:0
          });
          //跳转记录
          var s_type=3;
          if(that.data.tabId==1){
              s_type=2;
          }
          setTimeout(function(){
            wx.navigateTo({
              url: '/pages/my/leaveMsgList?s_type='+s_type
            });
          },1300);
        }
      },
      fail: function (res) {
        wx.hideLoading();
      }
    });
  },


  // 图片加载后判断图片宽高比例
  oneImageLoad(e) {
    const {
      width,
      height,
    } = e.detail
    let index = e.currentTarget.dataset.index;
    console.log("height:" + height + ".....width" + width + "....e:" + e)
    let isHeightModeArr = this.data.isHeightModeArr;
    if (height >= width) {
      isHeightModeArr[index] = true;
      this.setData({
        isHeightModeArr
      })
    }

  },
  //删除图片
  delFile(e) {
    let that = this;
    let delNum = e.currentTarget.dataset.index;
    let images = that.data.images;
    let isHeightModeArr = that.data.isHeightModeArr;
    images.splice(delNum, 1);
    isHeightModeArr.splice(delNum, 1);
    that.setData({
      images: images,
      isHeightModeArr: isHeightModeArr
    })
  },
  // 预览图片
  previewImage(e) {
    let that = this,
      imgsrc = e.currentTarget.dataset.presrc,
      arr = that.data.images
    //console.log(preArr)
    wx.previewImage({
      current: imgsrc,
      urls: arr
    })
  },
  previewImg(e) {
    var that = this;
    let arr = []
    let imgurl = e.currentTarget.dataset.imgUrl;
    e.currentTarget.dataset.arr.forEach(item => {
      arr.push(that.data.baseUrl + item)
    });

    wx.previewImage({
      current: imgurl, //当前图片地址
      urls: arr, //所有要预览的图片的地址集合 数组形式
      success: function (res) {},
      fail: function (res) {},
      complete: function (res) {},
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    var that = this;

    //获取缓存中的openid
    var openid = wx.getStorageSync('ly24_openid');

    if (openid == '') {
      //缓存中没有openid
      //获取所需页面信息
      wx.login({
        success: function (res) {
          if (res.code) {
            //发起网络请求
            wx.request({
              url: that.data.baseUrl + 'getOpenid.php',
              method: 'POST',
              data: {
                'code': res.code
              },
              header: {
                'content-type': 'application/x-www-form-urlencoded'
              },
              success: function (res) {
                //缓存微信openid
                wx.setStorageSync('ly24_openid', res.data.openid);
                that.setData({
                  openid: res.data.openid
                });

                //获取本页数据
                that.getMyLeaveMsgPageInfo(res.data.openid);
              },
              fail: function (res) {}
            });
          }
        }
      });
    } else {
      that.setData({
        openid: openid
      });

      //获取本页数据
      that.getMyLeaveMsgPageInfo(openid);
    }

    //调用分享
    that.getShareInfo();
  },

  //获取本业数据
  getMyLeaveMsgPageInfo(openid) {
    var that = this;
    wx.showLoading({
      title: '数据加载中...'
    })
    wx.request({
      url: that.data.baseUrl + 'getMyLeaveMsgPageInfo.php',
      method: 'POST',
      data: {
        'openid': openid
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        wx.hideLoading();
        if (res.data.status == 1) {
          //重新赋值后台请求数据
          that.setData({
            //list: res.data.list,
            imgMax: res.data.imgMax
          });
        } else {
          app.showTip(res.data.msg);
          setTimeout(function () {
            wx.navigateBack({
              delta: 1
            });
          }, 2000);
        }
      },
      fail: function () {
        wx.hideLoading();
        app.showTip('抱歉,服务器繁忙');
        setTimeout(function () {
          wx.navigateBack({
            delta: 1
          });
        }, 2000);
      }
    });
  },


  //获取微信分享信息
  getShareInfo() {
    var that = this;
    wx.request({
      url: that.data.baseUrl + 'getShareInfo.php',
      method: 'POST',
      data: {

      },
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        that.setData({
          shareTitle: res.data.shareTitle,
          shareImg: res.data.shareImg
        });
      },
      fail: function (res) {}
    });
  },

  //关闭指引
  closeZy() {
    this.setData({
      showPrivacy: false,
      showLogin: false,
      showWsInfoDom: false
    });
  },

  //点击查看协议指引
  handleOpenPrivacyContract() {
    // 打开隐私协议页面
    wx.openPrivacyContract({
      success: () => {}, // 打开成功
      fail: () => {}, // 打开失败
      complete: () => {}
    })
  },

  //点击同意协议
  handleAgreePrivacyAuthorization() {
    this.setData({
      showPrivacy: false,
      showPrivacyFlag: true
    });
    app.globalData.showPrivacyFlag = true;
  },
  goList(){
    var that=this;
    var s_type=3;
    if(that.data.tabId==1){
      s_type=2;
    }
    wx.navigateTo({
      url: '/pages/my/leaveMsgList?s_type='+s_type
    });
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    //更新showPrivacyFlag
    this.setData({
      showPrivacyFlag: app.globalData.showPrivacyFlag
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
    var that = this;
    return {
      title: that.data.shareTitle,
      path: '/pages/index/index',
      imageUrl: that.data.shareImg,
      success: function (res) {

      },
      fail: function (res) {

      }
    }
  }
})